package com.dan.inter.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {
	
	private static final Log LOG = LogFactory.getLog(FileUtil.class);

	public static List<String> filesUpload(MultipartFile[] files,HttpServletRequest request){
		List<String> list = new ArrayList<String>();
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
				// 保存文件
				list = saveFile(request, file, list);
			}
		}
		// 写着测试，删了就可以
		for (int i = 0; i < list.size(); i++) {
			System.out.println("图片路径：" + list.get(i));
		}
		return list;
	}
	private static List<String> saveFile(HttpServletRequest request, MultipartFile file, List<String> list) {
		// 判断文件是否为空
		if (!file.isEmpty()) {
			try {
				// 保存的文件路径(如果用的是Tomcat服务器，文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
				String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
						+ file.getOriginalFilename();
				LOG.info(filePath);
//				list.add(file.getOriginalFilename());
				list.add(filePath);
				File saveDir = new File(filePath);
				if (!saveDir.getParentFile().exists())
					saveDir.getParentFile().mkdirs();
				// 转存文件
				file.transferTo(saveDir);
				return list;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return list;
	}
}
